package com.nd.sdp.android.young.app.main.impl;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;

import com.nd.sdp.android.young.app.main.api.IPage;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final BottomNavigationView navigation = findViewById(R.id.navigation);
        ServiceLoader<Fragment> iterator = ServiceLoader.load(Fragment.class);
        final List<Fragment> fragments = new ArrayList<>();
        for (Iterator<Fragment> iterator1 = iterator.iterator(); iterator1.hasNext(); ) {
            final Fragment fragment = iterator1.next();
            IPage property = fragment.getClass().getAnnotation(IPage.class);
            if (property == null) {
                continue;
            }
            Menu menu = navigation.getMenu();
            MenuItem item = menu.add(property.title());
            int drawable = getResources().getIdentifier(property.iconName(), "drawable", getPackageName());
            item.setIcon(drawable);
            fragments.add(fragment);
        }
        navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int size = navigation.getMenu().size();
                int index = 0;
                for (int i = 0; i < size; i++) {
                    if (navigation.getMenu().getItem(i) == item) {
                        index = i;
                        break;
                    }
                }
                getSupportFragmentManager()
                        .beginTransaction()
                        .replace(R.id.content, fragments.get(index))
                        .commit();
                return true;
            }
        });
    }

}
